'use strict';

ionicTea.controller('settingCtrl', function ($scope, $state, $stateParams, $rootScope,$ionicActionSheet, $cordovaCamera, $ionicHistory, $ionicPopup, $timeout, HttpService, HttpUploadService, UserService, $window, ShareService) {

	//
	$scope.user = UserService.getUserAcceptCache();
	$scope.signature = $scope.user.signature;

	// 修改用户名
	$scope.saveName = function (nickname) {
		if (nickname != '' && nickname != 'undefined') {
			// const user = UserService.getUserAcceptCache();
			var callback = {
				success: function success() {
					$state.go('setting-personal');
				},
				failed: function failed() {}
			};

			HttpService({ name: 'user/set', params: { user_id: $scope.user.id, nickname: nickname }, callback: callback });
		}
	};

	// 修改签名
	$scope.saveSignature = function (signature) {
		if (signature != '' && signature != 'undefined') {
			// const user = UserService.getUserAcceptCache();
			var callback = {
				success: function success() {
					$state.go('setting-personal');
				},
				failed: function failed() {}
			};

			HttpService({ name: 'user/set', params: { user_id: $scope.user.id, signature: signature }, callback: callback });
		}
	};

	// 修改用户名
	var changeGender = function changeGender(gender) {
		var callback = {
			success: function success() {
				$state.go('setting-personal');
			},
			failed: function failed() {}
		};

		HttpService({ name: 'user/set', params: { user_id: $scope.user.id, gender: gender }, callback: callback });
	};

	// 修改地区
	$scope.getProvince = function (pid, popup) {
		var params = {};
		if (pid == null) {
			params = {};
			$scope.userPickAddress = [];
		} else {
			params = { pid: pid };
		}
		var callback = {
			success: function success(data) {
				$scope.resultList = data.result;
				if (data.result.length === 0 && popup != null) {
					popup.close();

					var params = {};

                    params.user_id = UserService.getUserAcceptCache().id;
                    params.province_id = $scope.userPickAddress[0].id;
                    params.city_id = $scope.userPickAddress[1].id;
                    params.county_id = $scope.userPickAddress[2].id;

                    var setCallback = {
                        success: function(){
                            $state.go('setting-personal');

                        },
                        failed: function() {
                            alert("请求失败，请重试!");
                        }
                    };

                    HttpService({ name: 'user/set', params: params, callback: setCallback });
				}
				// if( id != null ){
				// 	$scope.showResultList();
				// }
			},
			failed: function failed(err) {}
		};

		HttpService({ name: 'district/list', params: params, callback: callback });
	};

	$scope.showResultList = function () {
		if ($scope.resultList == null || $scope.resultList.length === 0) {
			$scope.getProvince();
		}
		// An elaborate, custom popup
		var myPopup = $ionicPopup.show({
			title: '请选择',
			templateUrl: 'templates/account/dialog/address-select-dialog.html',
			scope: $scope
		});

		myPopup.then(function (res) {});

		$scope.onSelected = function (x) {
			$scope.getProvince(x.id, myPopup);
			$scope.userPickAddress.push(x);
		};
	};

	$scope.shareApp = function () {
		ShareService.shareImgMsg('万茶邦是一款优秀的APP', ['http://7xrn7f.com1.z0.glb.clouddn.com/16-8-23/68947155.jpg']);
		// var textStr = '<div class="row "><div class="col"><div class="nav-circle"><div class="nav-circle-icon"></div><div class="nav-circle-label">朋友圈</div></div></div>';
		// textStr += '<div class="col"><div class="nav-circle"><div class="nav-circle-icon"></div><div class="nav-circle-label ">微信好友</div></div></div>';
		// textStr += '<div class="col"><div class="nav-circle"><div class="nav-circle-icon"></div><div class="nav-circle-label ">新浪微博</div></div></div>';
		// textStr += '<div class="col"><div class="nav-circle"><div class="nav-circle-icon"></div><div class="nav-circle-label ">QQ空间</div></div></div>';
		// textStr += '</div>';
		// textStr += '<div class="row "><div class="col"><div class="nav-circle"><div class="nav-circle-icon"></div><div class="nav-circle-label ">QQ好友</div></div></div>';
		// textStr += '<div class="col"><div class="nav-circle"><div class="nav-circle-icon"></div><div class="nav-circle-label ">复制链接</div></div></div>';
		// textStr += '<div class="col"></div>';
		// textStr += '<div class="col"></div>';
		// textStr += '</div>';
		// // Show the action sheet
		// var hideSheet = $ionicActionSheet.show({
		//
		// 	buttons: [{ text: textStr }],
		// 	cssClass: "user-sheet",
		// 	titleText: '<p class="setting-share-title">想要分享给谁</p>',
		// 	cancelText: 'Cancel',
		// 	cancel: function cancel() {
		// 		// add cancel code..
		// 	},
		// 	buttonClicked: function buttonClicked(index) {
		// 		return true;
		// 	}
		// });
		//
		// // For example's sake, hide the sheet after two seconds
		// $timeout(function () {
		// 	hideSheet();
		// }, 2000);
	};

	//地址
	if ($stateParams.isChooseAddress) {
		$scope.isEdit = false;
		$scope.isDelete = false;
	} else {
		$scope.isEdit = true;
		$scope.isDelete = true;
	}

	$scope.initAddress = function () {
		var user = UserService.getUserAcceptCache();

		var callback = {
			success: function success(data) {
				// 显示地址列表
				$scope.user_address = data;
			},
			failed: function failed(err) {}
		};

		HttpService({ name: 'user/address/list', params: { user_id: user.id }, callback: callback });
	};
	$scope.user_address = [];

	$scope.defaultAddress = {
		address: '1'
	};

	//选择地址
	$scope.selectAddress = function (addressItem) {};

	// 地址 删除地址
	function deleteAdrress(id) {
		var user = UserService.getUserAcceptCache();
		var callback = {
			success: function success(data) {
				$scope.initAddress();
			},
			failed: function failed(err) {}
		};

		HttpService({ name: 'user/address/delete',
			params: {
				user_id: user.id,
				address_id: id
			}, callback: callback });
	}

	// 设置默认地址的确认对话框
	$scope.showAddressDefaultConfirm = function (item) {

		if ($stateParams.isChooseAddress) {

			var userInfo = {
				realname: item.name,
				mobile: item.mobile,
				address: item.province.name + " " + item.city.name + " " + item.county.name + " " + item.address
			};
			$stateParams.orderInfo.userInfo = userInfo;

			$state.go('product-orderConfirm', { orderInfo: $stateParams.orderInfo, from_url: $stateParams.from_url, userInfo: userInfo });
			return;
		}

		var confirmPopup = $ionicPopup.confirm({
			title: '万茶帮',
			template: '将该地址设为默认地址?'
		});

		confirmPopup.then(function (res) {
			if (res) {
				setDefaultAddress(item.id);
			} else {}
		});
	};

	function setDefaultAddress(id) {
		var user = UserService.getUserAcceptCache();
		var callback = {
			success: function success(data) {
				$scope.initAddress();
			},
			failed: function failed(err) {
				alert('设置失败');
			}
		};

		HttpService({ name: 'user/address/setdefault',
			params: {
				user_id: user.id,
				address_id: id
			}, callback: callback });
	}

	$scope.goBack = function () {
		$rootScope.back();
	};

	// 删除地址的确认对话框
	$scope.showAddressDeleteConfirm = function (item) {
		var confirmPopup = $ionicPopup.confirm({
			title: '万茶帮',
			template: '是否要删除该地址?'
		});

		confirmPopup.then(function (res) {
			if (res) {
				deleteAdrress(item.id);
			} else {}
		});
	};

	// 地址编辑
	$scope.goToEditAddress = function (item) {
		$state.go('setting-address-add', { editAddress: item, isChooseAddress: $stateParams.isChooseAddress }, {});
	};

	//性别
	$scope.user_gender = [{ gender: "男", value: "1" }, { gender: "女", value: "2" }];

	//默认性别
	$scope.defaultGender = {
		gender: '0'
	};

	//选择性别
	$scope.selectGender = function (gender) {
		console.log(gender);
		changeGender(gender.value);
	};

	// 登出
	$scope.logout = function () {
		$window.localStorage.removeItem('user');
		$state.go('tab.main');
	};
});
ionicTea.controller('settingAddressCtrl', function ($scope, $rootScope, $state, $stateParams, $ionicActionSheet, $ionicPopup, $timeout, HttpService, UserService) {
	$scope.defaultProvince = "点击右箭头选择";
	$scope.userPickAddress = [];
	$scope.model = {};

	console.log('hi');
	console.log($stateParams);

	$scope.back = function() {
		$rootScope.back();
	}

	var isUpdateAddress = false;
	if ($stateParams.editAddress != null) {
		isUpdateAddress = true;
		$scope.model = {
			name: $stateParams.editAddress.name,
			phone: $stateParams.editAddress.mobile,
			zip: $stateParams.editAddress.postcode,
			addressDetail: $stateParams.editAddress.address
		};

		$scope.userPickAddress.push($stateParams.editAddress.province);
		$scope.userPickAddress.push($stateParams.editAddress.city);
		$scope.userPickAddress.push($stateParams.editAddress.county);

		var tempAddress = '';
		$scope.userPickAddress.forEach(function (a) {
			tempAddress += a.name.concat(' ');
		});
		$scope.defaultProvince = tempAddress;
	}

	//增加地址 api调用
	$scope.add_address = function (name, phone, zip, addressDetial) {
		var user = UserService.getUserAcceptCache();

		var callback = {
			success: function success(data) {
				$state.go('setting-address', {
					isChooseAddress: $stateParams.isChooseAddress
				}, { reload: true });
			},
			failed: function failed(err) {}
		};

		var funcName = isUpdateAddress ? 'user/address/update' : 'user/address/create';
		var address_id = $stateParams.editAddress == null ? '' : $stateParams.editAddress.id;

		HttpService({ name: funcName,
			params: {
				user_id: user.id,
				name: name,
				mobile: phone,
				province: $scope.userPickAddress[0].id,
				city: $scope.userPickAddress[1].id,
				county: $scope.userPickAddress[2].id,
				address: addressDetial,
				postcode: zip,
				address_id: address_id
			}, callback: callback });
	};

	$scope.getProvince = function (pid, popup) {
		var params = {};
		if (pid == null) {
			params = {};
			$scope.userPickAddress = [];
		} else {
			params = { pid: pid };
		}
		var callback = {
			success: function success(data) {
				$scope.resultList = data.result;
				if (data.result.length === 0 && popup != null) {
					popup.close();

					var tempAddress = '';
                    $scope.userPickAddress.forEach(function (a) {
                        tempAddress += a.name.concat(' ');
                    });
                    $scope.defaultProvince = tempAddress;

				}
				// if( id != null ){
				// 	$scope.showResultList();
				// }
			},
			failed: function failed(err) {}
		};

		HttpService({ name: 'district/list', params: params, callback: callback });
	};

	// Triggered on a button click, or some other target
	$scope.showResultList = function () {
		if ($scope.resultList == null || $scope.resultList.length === 0) {
			$scope.getProvince();
		}
		// An elaborate, custom popup
		var myPopup = $ionicPopup.show({
			title: '请选择',
			templateUrl: 'templates/account/dialog/address-select-dialog.html',
			scope: $scope
		});

		myPopup.then(function (res) {});

		$scope.onSelected = function (x) {
			$scope.getProvince(x.id, myPopup);
			$scope.userPickAddress.push(x);
		};
	};
});

ionicTea.controller('settingPersonalCtrl', function ($scope, $state, UserService) {
	var userCallback = {
		success: function success(user) {
			$scope.user = user;
		}
	};

	$scope.initDatas = function () {
		UserService.getUserMustRefresh(userCallback);
	};
});
